import React, { useState, useEffect, useRef } from 'react'
import StepsForm from '@/components/StepsForm/StepsForm'
import {
  Form,
  Input,
  message,
  Radio,
  Breadcrumb,
  Select,
  Space,
  Divider,
  Tooltip,
} from 'antd'
import Layout from './Layout'
import { createTask, nameRepeats } from '@/api/url'
import { useNavigate } from 'react-router-dom'
import CheckButtonGroup from '@/components/CheckButtonGroup'
import {
  reinforceMap,
  apply_sceneMap,
  reinforce_typeMap,
  reinforce_modelMap,
  reinforce_datasetMap,
} from './utils/statusMap'
import styles from './evaluationTask.module.scss'

const EvaluationTask = () => {
  const forms = useRef(null)
  const [step1Val, setStep1Val] = useState({})
  const [allVal, setAllVal] = useState({})
  const [reinforceOpt, setReinforceOpt] = useState(reinforceMap)
  const [selectedWay, setSelectedWay] = useState([])
  const navigate = useNavigate()

  const checkName = async ({ target }) => {
    const { value } = target
    const res = await nameRepeats({ name: value })
    if (res.error_code === 1) message.error(res.message)
  }

  useEffect(() => {
    forms.current.forms.step2.setFieldValue('reinforce_way', [])
  }, [step1Val.reinforce_type])

  return (
    <Layout>
      <Breadcrumb
        key="outer"
        items={[
          {
            title: <a href="/taskList">加固任务管理</a>,
          },
          {
            title: '新建加固任务',
          },
        ]}
      />
      <div className={`${styles.add} task-add`}>
        <StepsForm
          ref={forms}
          onFinish={(values) => {
            const body = {
              ...values,
              apply_scene: values.apply_scene * 1,
              reinforce_type: values.reinforce_type * 1,
              reinforce_model: values.reinforce_model * 1,
              reinforce_dataset: values.reinforce_dataset * 1,
            }
            return createTask({ ...body })
              .then((result) => {
                if (result?.error_code === 0) {
                  message.success('提交成功')
                  navigate('/taskList')
                } else if (result?.error_code === 1) {
                  message.error(result.message)
                }
              })
              .catch((err) => {
                console.log(err)
              })
          }}
          stepsProps={{
            type: 'navigation',
            size: 'small',
            style: {
              marginBottom: 28,
              boxShadow: '0px -1px 0 0 #e8e8e8 inset',
            },
          }}
        >
          <StepsForm.StepForm
            // layout="vertical"
            title="填写任务基本信息"
            name="step1"
            style={{ padding: '0 100px' }}
            onFinish={async (values) => {
              const res = await nameRepeats({ name: values.name })
              console.log(res)
              if (res.error_code === 1) throw message.error(res.message)
              setStep1Val(values)
              console.log('step1', values)
              const { apply_scene, reinforce_type } = values
              const opt = reinforceMap.filter(
                (item) =>
                  item.taskName === apply_scene &&
                  item.reinforce_way === reinforce_type
              )
              setReinforceOpt(opt)
            }}
          >
            <Space
              className={styles.form1}
              direction="vertical"
              size="middle"
              style={{
                display: 'flex',
              }}
            >
              <h3>填写任务基本信息</h3>
              <Form.Item
                name="name"
                label="任务名称"
                rules={[
                  { required: true, message: '请输入任务名称' },
                  {
                    min: 3,
                    max: 15,
                    message: '名称的长度必须介于 3 和 15 个字符之间。',
                  },
                ]}
              >
                <Input placeholder={'请输入'} onBlur={checkName} />
              </Form.Item>
              <h3>待测评任务</h3>
              <Space className={'taskSpace'} size={[30]}>
                <Form.Item
                  name="apply_scene"
                  label="选择应用场景"
                  rules={[{ required: true, message: '请选择应用场景' }]}
                >
                  <Radio.Group>
                    {Object.entries(apply_sceneMap).map((item, index) => {
                      return (
                        <Radio value={item[0]} key={index}>
                          {item[1]}
                        </Radio>
                      )
                    })}
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  name="reinforce_type"
                  label="选择加固方式"
                  rules={[{ required: true, message: '请选择加固方式' }]}
                >
                  <Radio.Group>
                    {Object.entries(reinforce_typeMap).map((item, index) => {
                      return (
                        <Radio value={item[0]} key={index}>
                          {item[1]}
                        </Radio>
                      )
                    })}
                  </Radio.Group>
                </Form.Item>
              </Space>

              <Form.Item
                label="备注"
                name="remark"
                rules={[{ max: 50, message: '描述的长度最多 50 个字符' }]}
              >
                <Input.TextArea
                  maxLength={50}
                  autoSize={{ minRows: 3 }}
                  placeholder="请输入"
                />
              </Form.Item>
            </Space>
          </StepsForm.StepForm>

          <StepsForm.StepForm
            name="step2"
            title="配置加固评测参数"
            onFinish={(values) => {
              setAllVal({ ...step1Val, ...values })
              const { reinforce_way } = values
              const selectName = reinforce_way.map((item) => {
                const opt = reinforceOpt.find((i) => i.method_name === item)
                return opt.name
              })
              // if(selectName?.length===0)
              setSelectedWay(selectName)
            }}
          >
            <h3>选择加固方法</h3>
            <h4>请选择想要使用的加固测评方法</h4>
            <div>
              <Form.Item
                name="reinforce_way"
                rules={[
                  {
                    required: true,
                    message: '请选择加固方法',
                  },
                ]}
              >
                {/* 加固方式为推理加固，则可进行多选 训练加固单选 */}
                <CheckButtonGroup
                  className={styles.container}
                  step1Val={step1Val}
                  options={reinforceOpt}
                  onChange={(value) => {
                    forms.current.forms.step2.setFieldValue(
                      'reinforce_way',
                      value
                    )
                  }}
                />
              </Form.Item>
            </div>
            <Divider />
            <h3>选择加固目标</h3>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Form.Item
                name="reinforce_model"
                label="选择训练/推理加固模型"
                style={{ width: '40%' }}
                rules={[{ required: true, message: '请选择训练/推理加固模型' }]}
              >
                <Select
                  placeholder="请选择"
                  options={[
                    {
                      value: '0',
                      label: '内置模型',
                    },
                  ]}
                />
              </Form.Item>
              <Space direction="vertical" style={{ width: '40%' }}>
                <Form.Item
                  name="reinforce_dataset"
                  label="选择数据集"
                  style={{ marginBottom: 0 }}
                  rules={[{ required: true, message: '请选择数据集' }]}
                >
                  <Select
                    placeholder="请选择"
                    options={[
                      {
                        value: '0',
                        label: '内置数据集',
                      },
                    ]}
                  />
                </Form.Item>
                <div
                  style={{ textAlign: 'center', color: 'rgba(15,29,53,0.35)' }}
                >
                  数据集将用于生产对抗样本模拟攻击来测评您的服务
                </div>
              </Space>
            </div>
          </StepsForm.StepForm>

          <StepsForm.StepForm
            name="step3"
            title="提交任务"
            style={{ padding: '0 100px' }}
          >
            <h5>任务名称</h5>
            <div className={styles.taskReview}>
              <span>应用场景：{apply_sceneMap[allVal.apply_scene]}</span>
              <span>加固方式：{reinforce_typeMap[allVal.reinforce_type]}</span>
            </div>
            <h5>加固测评方案</h5>
            <div className={styles.taskReview}>
              <Tooltip title={selectedWay.join('， ')}>
                <p className={styles.selectedWay}>
                  测评方法：{selectedWay.join('， ')}
                </p>
              </Tooltip>
            </div>
            <h5>加固目标</h5>
            <div className={styles.taskReview}>
              <span>
                模型名称：{reinforce_modelMap[allVal.reinforce_model]}
              </span>
              <span>
                数据集：{reinforce_datasetMap[allVal.reinforce_dataset]}
              </span>
            </div>
          </StepsForm.StepForm>
        </StepsForm>
      </div>
    </Layout>
  )
}
export default EvaluationTask
